package crawler.server;

import crawler.common.SiteData;
import crawler.handler.BongDaCrawlHandler;
import crawler.handler.CrawlHandler;
import crawler.impl.BetaBongDaComVnParser;
import crawler.impl.IOneParser;
import crawler.impl.Kenh14Parser;
import crawler.impl.NgoisaoParser;
import crawler.impl.TheThaoVnExpressParser;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;


public class CrawlServer implements Runnable {
    private static final Logger logger = Logger.getLogger(CrawlServer.class);
    private static CrawlServer _instance = null;
    private static final Lock createLock_ = new ReentrantLock();
    
    public static CrawlServer getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new CrawlServer();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }
    
    @Override
    public void run() {
        try {
            Kenh14Parser kenh14 = new Kenh14Parser();
            SiteData siteData1 = new SiteData(null, "http://kenh14.vn/star.chn",kenh14);
            
            IOneParser ione = new IOneParser();
            SiteData siteData2 = new SiteData(null, "http://ione.vnexpress.net/tin-tuc/showbiz",ione);

            NgoisaoParser ngoisao = new NgoisaoParser();
            SiteData siteData3 = new SiteData(null, "http://ngoisao.net/tin-tuc/hau-truong/showbiz-viet",ngoisao);

            List<SiteData> lstSao = new ArrayList<>();
            lstSao.add(siteData1);
            lstSao.add(siteData2);
            lstSao.add(siteData3);
            CrawlHandler.init(lstSao);
            
            TheThaoVnExpressParser thethaoVne = new TheThaoVnExpressParser();
            SiteData siteData4 = new SiteData(null,"http://thethao.vnexpress.net/tin-tuc/bong-da", thethaoVne);
            BetaBongDaComVnParser betaBongDaComVn = new BetaBongDaComVnParser();
            SiteData siteData5 = new SiteData(null,"http://beta.bongda.com.vn/cat/bong-da-tbn", betaBongDaComVn);
            SiteData siteData6 = new SiteData(null,"http://beta.bongda.com.vn/cat/bong-da-anh", betaBongDaComVn);

            List<SiteData> lstBongDa = new ArrayList<>();
            lstBongDa.add(siteData4);
            lstBongDa.add(siteData5);
            lstBongDa.add(siteData6);
            BongDaCrawlHandler.init(lstBongDa);
            
        } catch (Exception e) {
            logger.error("Cannot start web server: " + e.getMessage(), e);
            System.exit(1);
        }
    }
    public void stop() throws Exception {
        CrawlHandler.stopAll();
    }

}